import { Killer } from "../../funcObj/interface/HealthPoint";
import { Location } from "../../info/Predefine";
import GameManager from "../../manager/GameManager";
import PlayerManager from "../../manager/PlayerManager";
import Player from "../../player/Player";
import DestructibleFacility from "../DestructibleFacility";
import Mine from "../pulbicFacility/Mine";

const { ccclass, property } = cc._decorator;

/**
 * 采油机
 */
@ccclass
export default class OilWell extends DestructibleFacility {

    @property(Mine)
    mine: Mine = null;

    @property(cc.Animation)
    machine: cc.Animation = null;

    @property(cc.Animation)
    buildTip: cc.Animation = null;

    public get locations(): Location[] {
        return this.getComponent(Mine).locations;
    }
    public set locations(v: Location[]) {
        this.getComponent(Mine).locations = v;
    }

    protected onLoad(): void {
        this.init(null);
    }

    init(player: Player): void {
        if (player) {
            super.init(player);
            this.machine.node.active = true;
            this.machine.play(this.machine.getClips()[player.playerId].name);
            this.schedule(this.addPlayerOil.bind(this), 1, cc.macro.REPEAT_FOREVER);
            this.node.getComponentInChildren(cc.Collider).enabled = true;
        } else {
            this.player = null;
            this.machine.node.active = false;
            this.hpProgress.node.active = false;
            this.node.getComponentInChildren(cc.Collider).enabled = false;
            this.unscheduleAllCallbacks();
        }
    }

    addPlayerOil() {
        //播放获得矿石的动画
        let count = 5;
        this.mine.loseCount(count)
        this.player.oil += count;
        this.player == PlayerManager.instance.controllerPlayer && GameManager.instance.showResourceTips(2, count, this.node.position);
        if (this.mine.curCount == 0) {
            this.unscheduleAllCallbacks();
            this.machine.stop();
        }
    }

    die(killer: Killer): void {
        GameManager.instance.setFacilityMapArray(this.mine, this.node.position, false);
        let index = this.player.facilityArr[this.facilityType].findIndex((item) => item == this)
        this.player.facilityArr[this.facilityType].splice(index, 1);
        // 播放摧毁动画 
        GameManager.instance.addFacilityExploadEffect(this.facilityType, this.node.position, this.node.getContentSize());
        this.node.emit(DestructibleFacility.EventType.摧毁, this);
        this.init(null);
    }
}
